package interaction.servlet;
/**
* @author	gem
* 登录/注册
*/
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import po.User;
import service.impl.UserServiceImpl;

@WebServlet(description = "登录", urlPatterns = { "/login","/register" })
public class UserLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserLogin() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uri = request.getRequestURI();
		String[] m = uri.split("/");
		String operation = m[m.length-1];
		//根据请求的url，确定调用的方法
//		if(operation.equals("login")) {
//			login(request);
//		}
//		else if(operation.equals("register")) {
//			register(request);
//		}
		//返回给前端
		response.getWriter().append("Served at: ").append(operation);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	protected int login(HttpServletRequest request) {
		String userId = request.getParameter("userId");
		String password = request.getParameter("password");
		UserServiceImpl myUserService = new UserServiceImpl();
//		账户密码是否正确
		boolean loginRight = myUserService.loginIn(userId, password);
		if(loginRight) {return 0;}
//		检查是否存在该id
		boolean idExist = myUserService.existUser(userId);
		if(idExist) {return 1;}
		else {
//			用户输入id不存在
			return 2;
		}
	}
	protected int register(HttpServletRequest request) {
		String userId = request.getParameter("userId");
		String password = request.getParameter("password");
//		新建一个用户，账户密码用户设置，其余皆为空
		User newUser = new User(userId,password);
		UserServiceImpl myUserService = new UserServiceImpl();
//		插入新的账户
		boolean result = myUserService.addUser(newUser);
		//TODO   注册用户
		return result?0:1;
	}
}
